package com.fz.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fz.entity.Book;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by bai on 2017/6/28.
 */
@Controller @RequestMapping("/dow")
public class Test {

    @RequestMapping("/a.do")
    public ModelAndView show() {
        ModelAndView m = new ModelAndView();
        m.addObject("name", "lisi");
        m.setViewName("a");
        return m;
    }

    @RequestMapping("/upload.do")
    public ModelAndView upload(@RequestParam("file") MultipartFile[] uploads,
                               HttpServletRequest req) throws IOException {
        ModelAndView mv = new ModelAndView();
        String path = req.getServletContext().getRealPath("/upload/");
        File f = new File(path);
        if (!f.exists()) {
            f.mkdir();
        }
        List<String> nn = new ArrayList<String>();
        for (MultipartFile upload : uploads) {
            //文件原始名称(上传前的名称，存入数据库)
            String fileName = upload.getOriginalFilename();//获取上传文件名
            //System.out.println(fileName+"*****");
            //System.out.println(path+"+++++");
            System.out.println(upload.getSize() + "++++++++");
            if (upload.getSize() <= 10240) {
                nn.add(fileName);
                upload.transferTo(new File(path, fileName));
            } else {
                System.out.println("文件太大禁止上传");
            }
        }
        // mv.addObject("src",fileName);
        mv.addObject("nn", nn);
        mv.setViewName("a");
        return mv;
    }

    @RequestMapping("/bk.do")
    @ResponseBody
    public Object book() {

        return JSONObject.toJSON(new Book("《java基础》", 20, 1));
    }

    @RequestMapping("download.do")
    @ResponseBody
    public void down(HttpServletRequest request,
                     HttpServletResponse response
    ) throws Exception {

        request.setCharacterEncoding("UTF-8");
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        String storeName = request.getParameter("name");
        //获取项目根目录
        String ctxPath = request.getSession().getServletContext()
                .getRealPath("");

        //获取下载文件露肩
        String downLoadPath = request.getServletContext().getRealPath("/dowload/") + storeName;

        //获取文件的长度
        long fileLength = new File(downLoadPath).length();

        //设置文件输出类型
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment; filename="
                + new String(storeName.getBytes("utf-8"), "ISO8859-1"));
        //设置输出长度
        response.setHeader("Content-Length", String.valueOf(fileLength));
        //获取输入流
        bis = new BufferedInputStream(new FileInputStream(downLoadPath));
        //输出流
        bos = new BufferedOutputStream(response.getOutputStream());
        byte[] buff = new byte[2048];
        int bytesRead;
        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
            bos.write(buff, 0, bytesRead);
        }
        //关闭流
        bis.close();
        bos.close();
    }

    @RequestMapping("/down.do")
    public ResponseEntity<byte[]> down(HttpServletRequest req) throws IOException {
        String name = req.getParameter("name");
        String f = req.getServletContext().getRealPath("/dowload/") + name;
        File file = new File(f);
        byte[] body = null;
        InputStream is = new FileInputStream(file);
        body = new byte[is.available()];
        is.read(body);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attchement;filename=" + file.getName());
        HttpStatus statusCode = HttpStatus.OK;
        ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
        return entity;
    }

    @RequestMapping("/mydown.action")
    @ResponseBody
    public void mydown(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String fileName = req.getParameter("name");
        if (fileName == null) {
            resp.setCharacterEncoding("utf-8");
            PrintWriter out = resp.getWriter();
            out.print("没有下载的文件...");
            out.flush();
            out.close();
        } else {
            resp.setContentType("application/force-download");// 设置强制下载不打开
            String fn = new SimpleDateFormat("yyyyMMddhhmmssS").format(new Date()) + fileName.substring(fileName.lastIndexOf("."));
            resp.addHeader("Content-Disposition", "attachment;fileName=" + fn);// 设置文件名
            String path = req.getServletContext().getRealPath("/download/"); //文件下载源路径
            File file = new File(path, fileName);
            byte[] buf = new byte[10240];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = resp.getOutputStream();
                int i = bis.read(buf);
                while (i != -1) {
                    os.write(buf, 0, i);
                    i = bis.read(buf);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }


    }
}
